package cn.bellychang.wangzheng.lru;

import java.util.Arrays;

/**
 * @author ChangLiang
 * @date 2020/10/26
 */
public class ArrayLruCache<T> implements LruCache<T>{

    private T[] cacheArray;

    public static final Integer INITIAL_CAPACITY = 4;

    public ArrayLruCache() {
        cacheArray = (T[]) new Object[INITIAL_CAPACITY];
    }

    public ArrayLruCache(Integer capacity) {
        cacheArray = (T[]) new Object[capacity];
    }

    @Override
    public void putIntoCache(T t) {
        int index = getIndexFromCache(t);
        if (index == -1) {
            removeFromCache(cacheArray.length - 1);
            cacheArray[0] = t;
        } else {
            // 如果已经存在 要将其移动到最前面
            T temp = cacheArray[index];
            removeFromCache(index);
            cacheArray[0] = temp;
        }
    }

    @Override
    public T getFromCache(T t) {
        int index = getIndexFromCache(t);
        if (index == -1) {
            return null;
        }
        return cacheArray[index];
    }

    private int getIndexFromCache(T t) {
        for (int i = 0; i < cacheArray.length; i++) {
            if (t.equals(cacheArray[i])) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 将0 - index 内容向右推动一位
     * @param index
     */
    private void removeFromCache(int index) {
        // sub-array: 0 -> (index - 1)
        T[] temp = Arrays.copyOfRange(cacheArray, 0, index);
        for (int i = 0; i < temp.length; i++) {
            cacheArray[i + 1] = temp[i];
        }
    }

    @Override
    public String toString() {
        return "ArrayLruCache{" +
                "cacheArray=" + Arrays.toString(cacheArray) +
                '}';
    }
}
